package com.wkkmicro.wkkmall.product.service.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wkkmicro.common.utils.PageUtils;
import com.wkkmicro.common.utils.Query;

import com.wkkmicro.wkkmall.product.dao.CategoryDao;
import com.wkkmicro.wkkmall.product.entity.CategoryEntity;
import com.wkkmicro.wkkmall.product.service.CategoryService;


@Service("categoryService")
public class CategoryServiceImpl extends ServiceImpl<CategoryDao, CategoryEntity> implements CategoryService {

    @Autowired
    CategoryDao categoryDao;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<CategoryEntity> page = this.page(
                new Query<CategoryEntity>().getPage(params),
                new QueryWrapper<CategoryEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public List<CategoryEntity> listWithTree() {
//        1. 查出所有分类
//        baseMapper可以作为CategoryDao使用，其次我们也可以用autowired引入Dao层，第一种baseMapper请看extends ServiceImpl这个类
        List<CategoryEntity> listCats = categoryDao.selectList(null);
//        2. 组装成树形结构

        //2.1 先找到一级分类
//        List<CategoryEntity> level1Menus = listCats.stream().filter(categoryEntity ->
//                categoryEntity.getParentCid() == 0
//        ).collect(Collectors.toList());
        //2.2 类的私有方法找到分类的子分类（递归操作 可能会有好几层）

        List<CategoryEntity> level1Menus = listCats.stream().filter(categoryEntity ->
            categoryEntity.getParentCid() == 0
        ).map(menu -> {
            menu.setChildren(getChildrens(menu, listCats));
            return menu;
        }).sorted((a,b)->{
            return ( a.getSort() == null ? 0 : a.getSort())  - (b.getSort() == null ? 0 : b.getSort());
        }).collect(Collectors.toList());

        return level1Menus;
    }

    private List<CategoryEntity> getChildrens(CategoryEntity main, List<CategoryEntity> all)
    {
        List<CategoryEntity> children = all.stream().filter(categoryEntity -> {
            return categoryEntity.getParentCid() == main.getCatId();
        }).map(categoryEntity -> {
            //1 找到子菜单的子菜单
            categoryEntity.setChildren(getChildrens(categoryEntity,all));
            return categoryEntity;
        }).sorted((a,b)->{
            return ( a.getSort() == null ?  0 : a.getSort() )  - ( b.getSort() == null ? 0 : b.getSort());
        }).collect(Collectors.toList());

        //2 上面是第二步菜单的排序
        return children;
    }

}